import {BrowserWindow, shell} from 'electron'
import {join} from 'node:path'
const preload = join(__dirname, '../preload/index.js')
const url = process.env.VITE_DEV_SERVER_URL
const indexHtml = process.env.VITE_DEV_SERVER_URL||join(process.env.DIST, 'index.html')
let main: BrowserWindow | null = null

export async function createWindow() {
    main = new BrowserWindow({
        title: 'Main window',
        icon: join(process.env.VITE_PUBLIC, 'favicon.ico'),
        webPreferences: {
            preload,
            // Warning: Enable nodeIntegration and disable contextIsolation is not secure in production
            // Consider using contextBridge.exposeInMainWorld
            // Read more on https://www.electronjs.org/docs/latest/tutorial/context-isolation
            nodeIntegration: true,
            contextIsolation: false,
        },
    })

    if (process.env.VITE_DEV_SERVER_URL) { // electron-vite-vue#298
        await main.loadURL(url)
        // Open devTool if the app is not packaged
        main.webContents.openDevTools()
    } else {
        await main.loadFile(indexHtml)
    }

    // Test actively push message to the Electron-Renderer
    main.webContents.on('did-finish-load', () => {
        main?.webContents.send('main-process-message', new Date().toLocaleString())
    })

    // Make all links open with the browser, not with the application
    main.webContents.setWindowOpenHandler(({url}) => {
        if (url.startsWith('https:')) shell.openExternal(url)
        return {action: 'deny'}
    })
    // main.webContents.on('will-navigate', (event, url) => { }) #344
}

/**
 * 清空main_windows
 */
export const clear=()=>{
    main=null
}
/**
 * 窗口获取焦点
 */
export const focus=async ()=>{
    if (main) {
        // Focus on the main window if the user tried to open another
        if (main.isMinimized()) main.restore()
        main.focus()
    }else {
        await createWindow()
    }
}
